<!--
@license
Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->

<link rel="import" href="../lib/async.html">
<link rel="import" href="../lib/settings.html">
<link rel="import" href="../lib/debounce.html">

<script>
(function() {

  'use strict';

  Polymer.Base._addFeature({

    /**
     * Convenience method to run `querySelector` on this local DOM scope.
     *
     * This function calls `Polymer.dom(this.root).querySelector(slctr)`.
     *
     * @method $$
     * @param {string} slctr Selector to run on this local DOM scope
     * @return {Element} Element found by the selector, or null if not found.
     */
    $$: function(slctr) {
      return Polymer.dom(this.root).querySelector(slctr);
    },

    /**
     * Toggles a CSS class on or off.
     *
     * @method toggleClass
     * @param {String} name CSS class name
     * @param {boolean=} bool Boolean to force the class on or off.
     *    When unspecified, the state of the class will be reversed.
     * @param {HTMLElement=} node Node to target.  Defaults to `this`.
     */
    toggleClass: function(name, bool, node) {
      node = node || this;
      if (arguments.length == 1) {
        bool = !node.classList.contains(name);
      }
      if (bool) {
        Polymer.dom(node).classList.add(name);
      } else {
        Polymer.dom(node).classList.remove(name);
      }
    },

    /**
     * Toggles an HTML attribute on or off.
     *
     * @method toggleAttribute
     * @param {String} name HTML attribute name
     * @param {boolean=} bool Boolean to force the attribute on or off.
     *    When unspecified, the state of the attribute will be reversed.
     * @param {HTMLElement=} node Node to target.  Defaults to `this`.
     */
    toggleAttribute: function(name, bool, node) {
      node = node || this;
      if (arguments.length == 1) {
        bool = !node.hasAttribute(name);
      }
      if (bool) {
        Polymer.dom(node).setAttribute(name, '');
      } else {
        Polymer.dom(node).removeAttribute(name);
      }
    },

    /**
     * Removes a class from one node, and adds it to another.
     *
     * @method classFollows
     * @param {String} name CSS class name
     * @param {HTMLElement} toElement New element to add the class to.
     * @param {HTMLElement} fromElement Old element to remove the class from.
     */
    classFollows: function(name, toElement, fromElement) {
      if (fromElement) {
        Polymer.dom(fromElement).classList.remove(name);
      }
      if (toElement) {
        Polymer.dom(toElement).classList.add(name);
      }
    },

    /**
     * Removes an HTML attribute from one node, and adds it to another.
     *
     * @method attributeFollows
     * @param {String} name HTML attribute name
     * @param {HTMLElement} toElement New element to add the attribute to.
     * @param {HTMLElement} fromElement Old element to remove the attribute from.
     */
    attributeFollows: function(name, toElement, fromElement) {
      if (fromElement) {
        Polymer.dom(fromElement).removeAttribute(name);
      }
      if (toElement) {
        Polymer.dom(toElement).setAttribute(name, '');
      }
    },

    /**
     * Returns a list of nodes that are the effective childNodes. The effective
     * childNodes list is the same as the element's childNodes except that
     * any `<content>` elements are replaced with the list of nodes distributed
     * to the `<content>`, the result of its `getDistributedNodes` method.
     *
     * @method getEffectiveChildNodes
     * @return {Array<Node>} List of effctive child nodes.
     */
    getEffectiveChildNodes: function() {
      return Polymer.dom(this).getEffectiveChildNodes();
    },

    /**
     * Returns a list of elements that are the effective children. The effective
     * children list is the same as the element's children except that
     * any `<content>` elements are replaced with the list of elements
     * distributed to the `<content>`.
     *
     * @method getEffectiveChildren
     * @return {Array<Node>} List of effctive children.
     */
    getEffectiveChildren: function() {
      var list = Polymer.dom(this).getEffectiveChildNodes();
      return list.filter(function(n) {
        return (n.nodeType === Node.ELEMENT_NODE);
      });
    },

    /**
     * Returns a string of text content that is the concatenation of the
     * text content's of the element's effective childNodes (the elements
     * returned by <a href="#getEffectiveChildNodes>getEffectiveChildNodes</a>.
     *
     * @method getEffectiveTextContent
     * @return {Array<Node>} List of effctive children.
     */
    getEffectiveTextContent: function() {
      var cn = this.getEffectiveChildNodes();
      var tc = [];
      for (var i=0, c; (c = cn[i]); i++) {
        if (c.nodeType !== Node.COMMENT_NODE) {
          tc.push(Polymer.dom(c).textContent);
        }
      }
      return tc.join('');
    },

    queryEffectiveChildren: function(slctr) {
      var e$ = Polymer.dom(this).queryDistributedElements(slctr);
      return e$ && e$[0];
    },

    queryAllEffectiveChildren: function(slctr) {
      return Polymer.dom(this).queryDistributedElements(slctr);
    },

    /**
     * Returns a list of nodes distributed to this element's `<content>`.
     *
     * If this element contains more than one `<content>` in its local DOM,
     * an optional selector may be passed to choose the desired content.
     *
     * @method getContentChildNodes
     * @param {String=} slctr CSS selector to choose the desired
     *   `<content>`.  Defaults to `content`.
     * @return {Array<Node>} List of distributed nodes for the `<content>`.
     */
    getContentChildNodes: function(slctr) {
      var content = Polymer.dom(this.root).querySelector(slctr || 'content');
      return content ? Polymer.dom(content).getDistributedNodes() : [];
    },

    /**
     * Returns a list of element children distributed to this element's
     * `<content>`.
     *
     * If this element contains more than one `<content>` in its
     * local DOM, an optional selector may be passed to choose the desired
     * content.  This method differs from `getContentChildNodes` in that only
     * elements are returned.
     *
     * @method getContentChildNodes
     * @param {String=} slctr CSS selector to choose the desired
     *   `<content>`.  Defaults to `content`.
     * @return {Array<HTMLElement>} List of distributed nodes for the
     *   `<content>`.
     */
    getContentChildren: function(slctr) {
      return this.getContentChildNodes(slctr).filter(function(n) {
        return (n.nodeType === Node.ELEMENT_NODE);
      });
    },


    /**
     * Dispatches a custom event with an optional detail value.
     *
     * @method fire
     * @param {String} type Name of event type.
     * @param {*=} detail Detail value containing event-specific
     *   payload.
     * @param {Object=} options Object specifying options.  These may include:
     *  `bubbles` (boolean, defaults to `true`),
     *  `cancelable` (boolean, defaults to false), and
     *  `node` on which to fire the event (HTMLElement, defaults to `this`).
     * @return {CustomEvent} The new event that was fired.
     */
    fire: function(type, detail, options) {
      options = options || Polymer.nob;
      var node = options.node || this;
      detail = (detail === null || detail === undefined) ? {} : detail;
      var bubbles = options.bubbles === undefined ? true : options.bubbles;
      var cancelable = Boolean(options.cancelable);
      var useCache = options._useCache;
      var event = this._getEvent(type, bubbles, cancelable, useCache);
      event.detail = detail;
      if (useCache) {
        this.__eventCache[type] = null;
      }
      node.dispatchEvent(event);
      if (useCache) {
        this.__eventCache[type] = event;
      }
      return event;
    },

    __eventCache: {},

    // NOTE: We optionally cache event objects for efficiency during high
    // freq. opts. This option cannot be used for events which may have
    // `stopPropagation` called on them. On Chrome and Safari (but not FF)
    // if `stopPropagation` is called, the event cannot be reused. It does not
    // dispatch again.
    _getEvent: function(type, bubbles, cancelable, useCache) {
      var event = useCache && this.__eventCache[type];
      if (!event || ((event.bubbles != bubbles) ||
          (event.cancelable != cancelable))) {
        event = new Event(type, {
          bubbles: Boolean(bubbles),
          cancelable: cancelable
        });
      }
      return event;
    },


    /**
     * Runs a callback function asyncronously.
     *
     * By default (if no waitTime is specified), async callbacks are run at
     * microtask timing, which will occur before paint.
     *
     * @method async
     * @param {Function} callback The callback function to run, bound to `this`.
     * @param {number=} waitTime Time to wait before calling the
     *   `callback`.  If unspecified or 0, the callback will be run at microtask
     *   timing (before paint).
     * @return {number} Handle that may be used to cancel the async job.
     */
    async: function(callback, waitTime) {
      var self = this;
      return Polymer.Async.run(function() {
        callback.call(self);
      }, waitTime);
    },

    /**
     * Cancels an async operation started with `async`.
     *
     * @method cancelAsync
     * @param {number} handle Handle returned from original `async` call to
     *   cancel.
     */
    cancelAsync: function(handle) {
      Polymer.Async.cancel(handle);
    },

    /**
     * Removes an item from an array, if it exists.
     *
     * If the array is specified by path, a change notification is
     * generated, so that observers, data bindings and computed
     * properties watching that path can update.
     *
     * If the array is passed directly, **no change
     * notification is generated**.
     *
     * @method arrayDelete
     * @param {String|Array} path Path to array from which to remove the item
     *   (or the array itself).
     * @param {any} item Item to remove.
     * @return {Array} Array containing item removed.
     */
    arrayDelete: function(path, item) {
      var index;
      if (Array.isArray(path)) {
        index = path.indexOf(item);
        if (index >= 0) {
          return path.splice(index, 1);
        }
      } else {
        var arr = this._get(path);
        index = arr.indexOf(item);
        if (index >= 0) {
          return this.splice(path, index, 1);
        }
      }
    },

    /**
     * Cross-platform helper for setting an element's CSS `transform` property.
     *
     * @method transform
     * @param {String} transform Transform setting.
     * @param {HTMLElement=} node Element to apply the transform to.
     * Defaults to `this`
     */
    transform: function(transform, node) {
      node = node || this;
      node.style.webkitTransform = transform;
      node.style.transform = transform;
    },

    /**
     * Cross-platform helper for setting an element's CSS `translate3d`
     * property.
     *
     * @method translate3d
     * @param {number} x X offset.
     * @param {number} y Y offset.
     * @param {number} z Z offset.
     * @param {HTMLElement=} node Element to apply the transform to.
     * Defaults to `this`.
     */
    translate3d: function(x, y, z, node) {
      node = node || this;
      this.transform('translate3d(' + x + ',' + y + ',' + z + ')', node);
    },

    /**
     * Convenience method for importing an HTML document imperatively.
     *
     * This method creates a new `<link rel="import">` element with
     * the provided URL and appends it to the document to start loading.
     * In the `onload` callback, the `import` property of the `link`
     * element will contain the imported document contents.
     *
     * @method importHref
     * @param {string} href URL to document to load.
     * @param {Function} onload Callback to notify when an import successfully
     *   loaded.
     * @param {Function} onerror Callback to notify when an import
     *   unsuccessfully loaded.
     * @param {boolean} optAsync True if the import should be loaded `async`.
     *   Defaults to `false`.
     * @return {HTMLLinkElement} The link element for the URL to be loaded.
     */
    importHref: function(href, onload, onerror, optAsync) {
      var link = document.createElement('link');
      link.rel = 'import';
      link.href = href;
      var list = Polymer.Base.importHref.imported = 
        Polymer.Base.importHref.imported || {};
      var cached = list[link.href];
      var imprt = cached || link;
      var self = this;
      var loadListener = function(e) {
        e.target.__firedLoad = true;
        e.target.removeEventListener('load', loadListener);
        e.target.removeEventListener('error', errorListener);
        return onload.call(self, e);
      };
      var errorListener = function(e) {
        e.target.__firedError = true;
        e.target.removeEventListener('load', loadListener);
        e.target.removeEventListener('error', errorListener);
        return onerror.call(self, e);
      };
      if (onload) {
        imprt.addEventListener('load', loadListener);
      }
      if (onerror) {
        imprt.addEventListener('error', errorListener);
      }
      // if already loaded/erroed, fire 'fake' load/error event
      if (cached) {
        if (cached.__firedLoad) {
          cached.dispatchEvent(new Event('load'));
        }
        if (cached.__firedError) {
          cached.dispatchEvent(new Event('error'));
        }
      // otherwise put in dom!
      } else {
        list[link.href] = link;
        optAsync = Boolean(optAsync);
        if (optAsync) {
          link.setAttribute('async', '');
        }
        document.head.appendChild(link);
      }
      return imprt;
    },

    /**
     * Convenience method for creating an element and configuring it.
     *
     * @method create
     * @param {string} tag HTML element tag to create.
     * @param {Object} props Object of properties to configure on the
     *    instance.
     * @return {Element} Newly created and configured element.
     */
    create: function(tag, props) {
      var elt = document.createElement(tag);
      if (props) {
        for (var n in props) {
          elt[n] = props[n];
        }
      }
      return elt;
    },

    /**
     * Checks whether an element is in this element's light DOM tree.
     *
     * @method isLightDescendant
     * @param {?Node} node The element to be checked.
     * @return {Boolean} true if node is in this element's light DOM tree.
     */
    isLightDescendant: function(node) {
      return this !== node && this.contains(node) &&
          Polymer.dom(this).getOwnerRoot() === Polymer.dom(node).getOwnerRoot();
    },

    /**
     * Checks whether an element is in this element's local DOM tree.
     *
     * @method isLocalDescendant
     * @param {HTMLElement=} node The element to be checked.
     * @return {Boolean} true if node is in this element's local DOM tree.
     */
    isLocalDescendant: function(node) {
      return this.root === Polymer.dom(node).getOwnerRoot();
    }

  });

  /*
    We patch importHref under the CE polyfill for 2 separate reasons:
    (1) performance optimization: CE registrations upgrade the entire document
    tree including imports. Therefore if an import is loaded every element 
    registered will upgrade the entire doc tree. This is $ and is optimized 
    via batching to occur once at startup (before WebComponentsReady). We
    override importHref here so that we can batch upgrades until after the 
    import has loded, leveraging the same batching optimization.
    (2) the CE polyfill upgrades elements in HI in the wrong order. They upgrade
    after all scripts in the import have run rather than being interleaved with 
    them. Therefore, any script that depends on a previous custom element in 
    the import will fail. By deferring upgrades until after async imports load
    we reduce the chance of a problem because upgrade time dependencies are 
    no longer an issue. (e.g. `dom-module` is a registration time dependency 
    when `lazyRegister` is not used and it is specially handled in `dom-module`;
    `custom-style` is an upgrade time dependency native css properties are used).

  */
  if (!Polymer.Settings.useNativeCustomElements) {
    var importHref = Polymer.Base.importHref;
    Polymer.Base.importHref = function(href, onload, onerror, optAsync) {
      CustomElements.ready = false;
      var loadFn = function(e) {
        CustomElements.upgradeDocumentTree(document);
        CustomElements.ready = true;
        if (onload) {
          return onload.call(this, e);
        }
      }
      return importHref.call(this, href, loadFn, onerror, optAsync);
    }
  }

})();
</script>
